
'use strict';
const express = require('express');
const router = express.Router();

const resUtil = require("../module/util/resUtil");

/* GET home page. */
router.get('/', function(req, res, next) {
    res.redirect(global.config.path.contextPath+'/view/index');
});

router.use('*', function(req, res, next) {
    let language, loginFlag, dataFlag, local;

    if(req.query.local){
        local = req.query.local;
        req.session.local = local;
    }else if(req.session.local){
        local = req.session.local;
    }else{
        language = req.headers["accept-language"] || 'zh-CN';
        local = language.substr(0,2);
        req.session.local = local;
    }
    req.setLocale(local);

    // req.endType = "";
    req.endType = global.tool.endType(req.headers['user-agent']);

    req.defaultParam = {
        path : null,
        redirect : null,
        data : req.query || {},
        body : {},
        userData:req.session.userData,
        cookie : req.cookies,
        local : local,
    };

    //check login
    loginFlag = Boolean(req.session.userData);

    if(loginFlag){
        req.curUser = req.session.userData;
        next();
    }else{
        dataFlag = req.headers["ajax-flag"];
        if(dataFlag){
            res.send(resUtil.forbidden());
        }else{
            let redirectUrl = req.baseUrl;
            let flag = true;
            for(let key in req.query){
                if(flag){
                    redirectUrl+='?';
                    flag = false;
                }else{
                    redirectUrl+='&';
                }
                redirectUrl+=`${key}=${req.query[key]}`;
            }
            res.redirect(global.config.path.contextPath+'/login?redirect='+encodeURIComponent(redirectUrl));
        }
    }
});

module.exports = router;
